package com.masterclient.app.businessmodule.usermodule.login.index;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.usermodule.login.beans.AuthBindData;
import com.masterclient.app.businessmodule.usermodule.login.beans.InviteInfoData;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginBean;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginSuccessData;
import com.masterclient.app.businessmodule.usermodule.login.contract.SetNewPwdContract;
import com.masterclient.app.businessmodule.usermodule.login.contract.SetNewPwdPresenter;
import com.masterclient.app.businessmodule.usermodule.login.dialog.InviteDialog;
import com.masterclient.app.businessmodule.usermodule.login.invite.BindInviteActivity;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 作者：Hxm
 * 创建时间：2019/12/17
 * 功能说明：
 */
@Route(path = AroutePath.SET_NEW_PED_FRAGMENT)
public class SetNewPwdActivity extends FCBusinessActivity<SetNewPwdPresenter> implements SetNewPwdContract.View {

    @BindView(R.id.iv_pwd_show)
    ImageView ivPwdShow;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.et_pwd2)
    EditText etPwd2;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.scroll)
    ScrollView scrollView;



    @Autowired(name = "phone")
    String phoneNum;
    @Autowired(name = "code")
    String verifyCode;
    @Autowired(name = "intentSource")
    String intentSource;
    private boolean isSelected = false;
    boolean isPwdShow = false;
    private String pwd;
    private String rewardId = "";


    @Override
    protected int requireGetLayoutId() {
        return R.layout.fragment_set_new_pwd;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setLineHidden(true);
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {

        ivPwdShow.setOnClickListener(v -> {
            if (isPwdShow) {
                ivPwdShow.setImageResource(R.mipmap.hide_icon_login);
                isPwdShow = false;
                etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                ivPwdShow.setImageResource(R.mipmap.show_icon_login);
                isPwdShow = true;
                etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            if (!TextUtils.isEmpty(etPwd.getText().toString())) {
                etPwd.setSelection(etPwd.getText().toString().length());
            }
        });

        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() >= 6 && etPwd2.getText().toString().length() >= 6) {
                    tvLogin.setClickable(true);
                    tvLogin.setBackgroundResource(R.drawable.login_able_click_bkg);
                    tvLogin.setTextColor(0xffffffff);
                } else {
                    tvLogin.setClickable(false);
                    tvLogin.setBackgroundResource(R.drawable.login_unable_click_bkg);
                    tvLogin.setTextColor(0xffffffff);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etPwd2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() >= 6 && etPwd.getText().toString().length() >= 6) {
                    tvLogin.setClickable(true);
                    tvLogin.setBackgroundResource(R.drawable.login_able_click_bkg);
                    tvLogin.setTextColor(0xffffffff);
                } else {
                    tvLogin.setClickable(false);
                    tvLogin.setBackgroundResource(R.drawable.login_unable_click_bkg);
                    tvLogin.setTextColor(0xffffffff);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        scrollToShowSubmitBtn(scrollView);
        etPwd.setOnClickListener(view -> scrollToShowSubmitBtn(scrollView));
        etPwd.setOnTouchListener((view, motionEvent) -> {
            scrollToShowSubmitBtn(scrollView);
            return false;
        });

        etPwd2.setOnClickListener(view -> scrollToShowSubmitBtn(scrollView));
        etPwd2.setOnTouchListener((view, motionEvent) -> {
            scrollToShowSubmitBtn(scrollView);
            return false;
        });
    }

    /**
     * 使滚动条滚动至指定位置（垂直滚动）
     *
     * @param scrollView 要滚动的ScrollView
     * @param to         滚动到的位置
     */
    protected void scrollVertical(final ScrollView scrollView, final int to) {
        scrollView.postDelayed(() -> scrollView.scrollTo(0, to),100);
    }

    /**
     * 使ScrollView滚动至底部，显示Submit按钮
     *
     * @param scrollView 要滚动的scrollView
     */
    protected void scrollToShowSubmitBtn(final ScrollView scrollView) {
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        scrollView.postDelayed(() -> scrollVertical(scrollView, scrollView.getHeight()), 100);
    }

    @OnClick({R.id.tv_login})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login:

                pwd = etPwd.getText().toString().trim();
                String pw2 = etPwd2.getText().toString().trim();
                if (!pwd.equals(pw2)) {
                    ToastUtil.showToast("两次密码不一致");
                    return;
                }
                mPresenter.forgotSetPwd(verifyCode,phoneNum,pwd,"forget_password");
                break;

        }
    }

    @Override
    public void setPwdSuccess(LoginSuccessData data) {
        login_success_next(data);
    }

    LoginSuccessData data;
    private void login_success_next(LoginSuccessData data) {
        if(!TextUtils.isEmpty(data.getCustomer_id())){
            SPUtils.getInstance().put(Config.CUSTOMERID_TEMP, data.getCustomer_id());
        }
        if(!TextUtils.isEmpty(data.getToken())){
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN_TEMP, data.getToken());
        }
        UserDataManager.getInstance().updateUserStatus(data.isIs_disable());
        this.data = data;
        if (data.getInviter_code_select_pop() != null && data.getInviter_code_select_pop().bindInviterCode != null){
            rewardId = data.getInviter_code_select_pop().bindInviterCode.rewardId;
        }
        if (data.isIs_disable()) {
            SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
            UtilActivity.finishStartNum(0, UtilActivity.getActivitySize());
            ARouter.getInstance().build(AroutePath.BAN_ACCOUNT_ACTIVITY)
                    .withString("content", data.getFreeze_reason()).navigation();
        }else if (data.isIs_show_code_select_pop() || data.isIs_show_user_info_pop()) {
            //绑定邀请人弹窗
            //TODO:fix
            //绑定邀请人弹窗
            Intent intent = new Intent(getActivity(), BindInviteActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("auth_type", "");
            bundle.putString("phone", phoneNum);
            bundle.putString("union_id", "");
            bundle.putString("nick_name", "");
            bundle.putString("headimgurl", "");
            bundle.putSerializable("inviter_pop", data.getInviter_pop());
            bundle.putSerializable("lg_data",data);
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BindInviteActivity.REQUEST_CODE);

        }else {
            //已绑定
            login_success_convert();
        }
    }

    private void login_success_convert() {
        showToast("登录成功");
        SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
        SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
        UserDataManager.getInstance().updateUserStatus(data.isIs_disable());
        EventBusManager.post(EventBusManager.createLoginSuccessEvent());
        EventBusManager.post(EventBusManager.createHomeRefreshEvent());
        getActivity().finish();
        if (!UtilActivity.isCurActivity("MainActivity")) {
            startActivitryWithBundle(MainActivity.class, null);
        }
    }

    private InviteDialog dialog;
    private void show_pop_dialog(LoginSuccessData data) {
        if (dialog == null) {
            dialog = new InviteDialog(getActivity(), new InviteDialog.OnChooseListener() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void getByInviteCode(String invite_code) {
                    mPresenter.getInviteInfo(invite_code);
                }

                @Override
                public void confirm(String inviteCode) {
                    //dialog.dismiss();
                    baseShowCommitLoading("登录中");
                    mPresenter.authBind("",phoneNum, "",inviteCode,Config.uid,"","",
                            data.getNonce(),SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP),rewardId);

                }

                @Override
                public void skip_login() {
                    login_success_convert();
                }
            });
        }
        dialog.show();
        dialog.setData(data);
    }

    @Override
    public void setPwdFailed(String msg, String failReason) {
        showToast(msg);
    }

    @Override
    public void loginSuccess(LoginBean.LoginData data) {
        showToast("登录成功");
//        getActivity().finish();
        Observable.just("s").delay(1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(s->{
            SPUtils.getInstance().put(Config.CUSTOMERID,data.getSh_customer_id());
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN,data.getSh_token());
            UserDataManager.getInstance().updateUserStatus(data.getSh_is_disable());
            EventBusManager.post(EventBusManager.createLoginSuccessEvent());
            EventBusManager.post(EventBusManager.createHomeRefreshEvent());
            getActivity().finish();
            if ("1".equals(data.getSh_is_disable())){
                UtilActivity.finishStartNum(0,UtilActivity.getActivitySize());
                ARouter.getInstance().build(AroutePath.BAN_ACCOUNT_ACTIVITY)
                        .withString("content",data.getSh_freeze_reason()).navigation();
            }else {
                if (!UtilActivity.isCurActivity("MainActivity")){
                    startActivitryWithBundle(MainActivity.class,null);
                }
            }
//            }
        });
    }

    @Override
    public void loginFailed() {
        showToast("登录失败");
    }

    @Override
    public void showInviteInfo(InviteInfoData inviteInfoData) {
        rewardId = "";
        dialog.refreshInviteInfo(inviteInfoData,"");
    }

    @Override
    public void showInviteInfoFail(String msg) {
        dialog.refreshErrorInfo(msg);
    }

    @Override
    public void authBindSuccess(String code,AuthBindData data,String msg,String inviteCode) {
        UserDataManager.getInstance().updateInviteCode(inviteCode);
        if ("30000".equals(code)){
            rewardId = data.getInviteInfo().getReward_id();
            dialog.refreshInviteInfo(data.getInviteInfo(),data.getNotice());
        }else {
            if(dialog != null){
                dialog.dismiss();
            }
            if (data != null) {
                if(!TextUtils.isEmpty(data.getCustomer_id())){
                    SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
                }else {
                    SPUtils.getInstance().put(Config.CUSTOMERID, SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP));
                }
                if(!TextUtils.isEmpty(data.getToken())){
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
                }else{
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN_TEMP));
                }
            }
            EventBusManager.post(EventBusManager.createLoginSuccessEvent());
            EventBusManager.post(EventBusManager.createHomeRefreshEvent());
            getActivity().finish();
            if (!UtilActivity.isCurActivity("MainActivity")){
                startActivitryWithBundle(MainActivity.class,null);
            }
        }
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    public void authBindFailded(String msg) {
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BindInviteActivity.REQUEST_CODE) {
            if (resultCode == BindInviteActivity.BIND_SUC_CODE) {
                getActivity().finish();
                if (!UtilActivity.isCurActivity("MainActivity")) {
                    startActivitryWithBundle(MainActivity.class, null);
                }
            }
        }
    }

}
